﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: Mode.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-09-06 11:39 AM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

namespace BOL.Linq.Descriptive
{
    public static partial class Descriptive
    {
        public static T? Mode<T>(this IEnumerable<T> source)
            where T : struct
        {
            var count = 0;
            var max = 0;
            var current = default(T);
            var mode = new T?();

            foreach (var next in source.OrderBy(x => x))
            {
                if (current.Equals(next))
                    count++;
                else
                {
                    current = next;
                    count = 1;
                }

                if (count > max)
                {
                    max = count;
                    mode = current;
                }
            }

            return max > 1 ? mode : null;
        }

        public static TMode? Mode<TSource, TMode>(this IEnumerable<TSource> source, Func<TSource, TMode> selector)
            where TMode : struct
        {
            return source.Select(selector).Mode();
        }
    }
}
